/*
场景控制器
*/

layui.define(['layer','form','element','cosjs'], function (exports) {
    let $ = layui.jquery, layer = layui.layer , cosjs = layui.cosjs,form = layui.form, element = layui.element;

    function scene() {
        this.root = '/';
    }

    //获取场景控制器
    scene.prototype.get = function(id){
        let path = ['scene/handle',id].join('/');
        return Promise.resolve(1).then(()=>{
            if(!layui[id]){
                let opts = {}; 
                opts[id] = ['{/}',scene.root,path].join('');
                layui.extend(opts);
            }
            return cosjs.promise(layui_use_promise,id);
        })
    }
    scene.prototype.view = function(id){
        let path = ['scene/view',id].join('/') ,data = arguments[1]||{};
        let url = [this.root,path,'.html'].join('') ;
        let opts = {'dataType':'text'}
        return cosjs.get(url,{},opts).then(view=>{
            return ejs.render(view, data);
        })
    }
    
    //切换主场景
    scene.prototype.show = function(id,args){
        let model,data,html;
        return this.get(id).then(ret=>{
            model = ret;
            if(typeof model === 'function'){
                return model.call(this,args);
            }
            else{
                return model|| args
            }
        }).then(ret=>{
            data = ret;
            return this.view(id,data);
        }).then(ret=>{
            html = ret;
            $('body').html(html);
            form.render();element.render();
        }).then(()=>{
            if(typeof model['finish'] === 'function'){
                model['finish'].call(this,data);
            }
        }).then(()=>{
            return model;
        })
    }

    //对话框
    scene.prototype.dialog = function(id,args){
        let model,data;
        let opts = { 'shade':0,'btn':'','area': ['500px', '300px'] };
        return this.get(id).then(ret=>{
            model = ret;
            if(typeof model === 'function'){
                return model.call(this,args);
            }
            else{
                return model|| args
            }
        }).then(ret=>{
            data = ret;
            return this.view(id,data);
        }).then(ret=>{
            opts['content'] = ret;
            if(typeof model['dialog'] === 'function'){
                return model['dialog'].call(this,data)
            }
            else {
                return null;
            }

        }).then(ret=>{
            if(ret){
                Object.assign(opts,ret);
            }
            layer.open(opts);
            form.render();element.render();
        }).then(()=>{
            if(typeof model['finish'] === 'function'){
                model['finish'].call(this,data);
            }
        })
    }

    function layui_use_promise(key,callback){
        layui.use(key,function(){
            callback(null,layui[key]);
        })
    }

    exports('scene', new scene);
})